package com.mid;

import javafx.util.Pair;

import java.util.*;

/**
 * Created by Lxk on 2020/2/18.
 */
public class Solution347 {


    public List<Integer> topKFrequent(int[] nums, int k) {
        List<Integer> res = new ArrayList<>();
        if (nums == null || nums.length == 0) {
            return res;
        }
        Map<Integer, Integer> countMap = new HashMap<>();
        for (Integer val : nums) {
            if (countMap.keySet().contains(val)) {
                countMap.put(val, countMap.get(val) + 1);
            } else {
                countMap.put(val, 0);
            }
        }
        PriorityQueue<Pair<Integer, Integer>> pairPriorityQueue = new PriorityQueue<>((p1, p2) ->
                p2.getValue() - p1.getValue()
        );
        for (Map.Entry<Integer, Integer> entry : countMap.entrySet()) {
            pairPriorityQueue.offer(new Pair<>(entry.getKey(), entry.getValue()));
        }
        for (int i = 0; i < k; i++) {
            res.add(pairPriorityQueue.poll().getKey());
        }
        return res;
    }

    public static void main(String[] args) {
        int[] arr = {1, 1, 1, 2, 2, 3};
        Solution347 solution347 = new Solution347();
        System.out.println(solution347.topKFrequent(arr, 2));
    }

}
